import { defineStore } from 'pinia'

export const useOrderStore = defineStore('order', () => {
  const orders = ref<ApiOrderProductInfo[]>([])

  const currOrderId = ref<number>()

  function cleanOrders() {
    orders.value = []
    currOrderId.value = undefined
  }

  function addOrder(order2Add: ApiOrderProductInfo) {
    orders.value.push(order2Add)
    currOrderId.value = order2Add.id
  }

  function plusOrder() {
    const order = orders.value.find(o => o.id == currOrderId.value)
    if (order) {
      order.amount += 1
    }
  }

  function minusOrder() {
    const order = orders.value.find(o => o.id == currOrderId.value)
    if (order) {
      if (order.amount > 1) {
        order.amount -= 1
      } else {
        orders.value = orders.value.filter(o => o.id != currOrderId.value)
        currOrderId.value = orders.value.length > 0 ? orders.value[orders.value.length - 1].id : undefined
      }
    }
  }

  function changeOpt(id: number, type: number, value: any) {
    const order = orders.value.find(o => o.id == id)
    if (order) {
      if (type == 0) {
        order.size = value.name
        order.price = value.price
      } else if (type == 1) {
        order.cold = value
      } else {
        order.sugar = value
      }
    }
  }

  return {
    orders,
    currOrderId,
    cleanOrders,
    addOrder,
    plusOrder,
    minusOrder,
    changeOpt
  }
})
